package com.itheima.sfbx.framework.aspect;

import com.alibaba.fastjson.JSONObject;
import com.itheima.sfbx.framework.anno.SensitiveResponse;
import com.itheima.sfbx.framework.commons.utils.EmptyUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Type;

/**
 * @ClassName SensitiveAspect.java
 * @Description TODO
 */
@Aspect
@Component
public class SensitiveAspect {

    @Around(value = "@annotation(sensitiveResponse)")
    public Object select(ProceedingJoinPoint joinPoint, SensitiveResponse sensitiveResponse) throws Throwable {
        //TODO
        //拿到方法的返回值
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();//方法签名
        Type returnType = signature.getMethod().getGenericReturnType();//方法的返回值带泛型
        Object result = joinPoint.proceed();//执行目标方法,result就是目标方法的返回值
        if (!EmptyUtil.isNullOrEmpty(result)) {
            String jsonString = JSONObject.toJSONString(result);
            String resultJson = maskSensitiveData(jsonString);
            return JSONObject.parseObject(resultJson, returnType);//需要直到它真正的返回值类型
        }
        //返回
        return result;
    }


    private String maskSensitiveData(String jsonData) {
        //使用正则表单式替换，我也不会写~~直接GPT搞定！
        return jsonData
                .replaceAll("\"identityCard\"\\s*:\\s*\"(\\d{1})(\\d{15})(\\d{2})\"", "\"identityCard\":\"$1**************$3\"")
                .replaceAll("\"name\"\\s*:\\s*\"(.).+?\"", "\"name\":\"$1*\"")
                .replaceAll("\"bankCardNo\"\\s*:\\s*\"(.).+?\"", "\"bankCardNo\":\"$1*\"")
                .replaceAll("\"bankName\"\\s*:\\s*\"(.).+?\"", "\"bankName\":\"$1*\"")
                .replaceAll("\"bankReservedPhoneNum\"\\s*:\\s*\"(.).+?\"", "\"bankReservedPhoneNum\":\"$1*\"");
    }
}
